package edu.whu.controller;

import edu.whu.bean.Product;
import edu.whu.bean.Supplier;
import edu.whu.dao.ProductMapper;
import edu.whu.exception.ExceptionResponse;
import edu.whu.exception.ProductException;
import edu.whu.service.ProductService;
import edu.whu.service.impl.ProductServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {
    private final ProductService service;
    @Autowired
    public ProductController(ProductMapper mapper) {
        this.service = new ProductServiceImpl(mapper);
    }

    @GetMapping("/select")
    public Product select(int id){
        return service.selectById(id);
    }

    @GetMapping("/select/all")
    public List<Product> selectAll(){
        return service.selectAll();
    }

    @GetMapping("/select/suppliers")
    public List<Supplier> selectSuppliers(int id){
        return service.selectSupplier(id);
    }

    @GetMapping("/add")
    public int add(Integer id, String name, Double price, Integer count, Integer sales){
        return service.insert(new Product(id,name,price,count,sales));
    }

    @GetMapping("/delete")
    public ResponseEntity<Object> delete(int id){
        try {
            service.deleteById(id);
            return ResponseEntity.ok().build();
        } catch (ProductException e) {
            ExceptionResponse response = new ExceptionResponse();
            response.setMessage(e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }
    }
}
